//
//  LLAudioNetwork.m
//  LLFoundation
//
//  Created by my_liu on 2016/11/14.
//  Copyright © 2016年 . All rights reserved.
//

#import "LLAudioNetwork.h"
#import "LLNWFileUploadManager+IMServer.h"
#import "LLLoggerUitilsMacrocDefine.h"

@interface LLAudioNetwork ()

@property (nonatomic,strong)NSMutableArray *uploadTasksArray;

@property (nonatomic,strong)NSMutableArray *downloadTasksArray;

@end

@implementation LLAudioNetwork

- (id)init
{
    if (self = [super init]) {
        
        self.uploadTasksArray = [[NSMutableArray alloc]init];
        self.downloadTasksArray = [[NSMutableArray alloc]init];
        
        /* 设定任务上传组件 */
        [self setAudioUploadManager];
        
        /* 延迟一秒观察任务下载任务观察 */
        [self performSelector:@selector(observeDownloadTask) withObject:nil afterDelay:1.f];
    }
    return self;
}

- (void)dealloc
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [[LLNWFileDownloadManager shareDownloadManager]clearTaskBlockForObserver:self];
}

#pragma mark - 上传任务观察
- (void)setAudioUploadManager
{
    if (self.uploadManager) {
        self.uploadManager = nil;
    }
    self.uploadManager = [LLNWFileUploadManager imServerUploadManager];
    
    /* 设定任务观察 */
    [self observeUploadTask];
}

- (void)observeUploadTask
{
    __weak typeof(self)weakSelf = self;
    
    [self.uploadManager setCompletionBlock:^(LLNWFileUploadTask *task, NSDictionary *resultDict) {
        
        NSDictionary *result = [resultDict objectForKey:@"result"];
        
        [weakSelf uploadCompletionWithTask:task resultDict:result];
        
    }];
    
    [self.uploadManager setProgressBlock:^(LLNWFileUploadTask *updateTask, CGFloat progressValue) {
        
        [weakSelf uploadProgressWithTask:updateTask progress:progressValue];
    }];
    
    [self.uploadManager setFaildBlock:^(LLNWFileUploadTask *task, NSError *error) {
        
        [weakSelf uploadFaildWithTask:task faild:error];
        
    }];
}

#pragma mark - 上传任务处理
- (void)uploadCompletionWithTask:(LLNWFileUploadTask *)task resultDict:(NSDictionary *)result
{
    LLAudioModel *originFile = task.userInfo[@"audioFile"];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(audioNetwork:formateUploadResult:formateDict:)]) {
        
        LLAudioModel  *formatedModel = [self.delegate audioNetwork:self formateUploadResult:originFile formateDict:result];
        
        if (formatedModel) {
            
            formatedModel.isBeenUploaded = YES;
            
            if (self.delegate && [self.delegate respondsToSelector:@selector(audioNetwork:finishUploadAudioFile:)]) {
                
                [self.delegate audioNetwork:self finishUploadAudioFile:formatedModel];
            }
            
        }else{
            
            LLAudioModel *originFile = task.userInfo[@"audioFile"];
            
            if (self.delegate && [self.delegate respondsToSelector:@selector(audioNetwork:forAudioFile:uploadFaild:)]) {
                
                NSError *serverError = [NSError errorWithDomain:@"http://www.wanmei.com" code:-123 userInfo:@{@"msg": @"参数非法"}];
                [self.delegate audioNetwork:self forAudioFile:originFile.localStorePath uploadFaild:serverError];
            }
            
        }
    }
}

- (void)uploadProgressWithTask:(LLNWFileUploadTask *)task progress:(CGFloat)progress
{
    LLAudioModel *originFile = task.userInfo[@"audioFile"];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(audioNetwork:forAudioFile:uploadProgress:)]) {
        
        [self.delegate audioNetwork:self forAudioFile:originFile.localStorePath uploadProgress:progress];
        
    }
}

- (void)uploadFaildWithTask:(LLNWFileUploadTask *)task faild:(NSError *)error
{
    LLAudioModel *originFile = task.userInfo[@"audioFile"];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(audioNetwork:forAudioFile:uploadFaild:)]) {
        
        [self.delegate audioNetwork:self forAudioFile:originFile.localStorePath uploadFaild:error];
    }
}

#pragma mark - 下载任务观察
- (void)observeDownloadTask
{
    __weak typeof(self)weakSelf = self;
    [[LLNWFileDownloadManager shareDownloadManager]setDownloadCompletionBlock:^(LLNWFileDownloadTask *task, NSData *fileData, BOOL isFinishCache) {
        
        [weakSelf downloadCompletion:task withFileData:fileData isFinishCached:isFinishCache];
        
    } forObserver:self];
    
    [[LLNWFileDownloadManager shareDownloadManager]setDownloadProgressBlock:^(LLNWFileDownloadTask *task, CGFloat progress) {
        
        [weakSelf downloadProgress:task withPorgress:progress];
        
    } forObserver:self];
    
    [[LLNWFileDownloadManager shareDownloadManager]setDownloadFaildBlock:^(LLNWFileDownloadTask *task, NSError *error) {
        
        [weakSelf downloadFaild:task faild:error];
        
    } forObserver:self];
}

#pragma mark - 下载具体处理
- (void)downloadCompletion:(LLNWFileDownloadTask *)task withFileData:(NSData *)fileData isFinishCached:(BOOL)finishCache
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(audioNetwork:finishDownloadWithAudioFile:)]) {
        
        LLAudioModel *audioFile = task.userInfo[@"audioFile"];
        
        [self.delegate audioNetwork:self finishDownloadWithAudioFile:audioFile];
    }
}

- (void)downloadProgress:(LLNWFileDownloadTask *)task withPorgress:(CGFloat)progress
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(audioNetwork:forAudioFile:downloadProgress:)]) {
        
        LLAudioModel *audioFile = task.userInfo[@"audioFile"];
        
        [self.delegate audioNetwork:self forAudioFile:audioFile.uniqueIdentifier downloadProgress:progress];
    }
}

- (void)downloadFaild:(LLNWFileDownloadTask *)task faild:(NSError *)error
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(audioNetwork:forAudioFile:downloadFaild:)]) {
        
        LLAudioModel *audioFile = task.userInfo[@"audioFile"];
        
        [self.delegate audioNetwork:self forAudioFile:audioFile.remotePath downloadFaild:error];
        
    }
    
}

- (void)uploadAudioFile:(LLAudioModel *)audioFile
{
    NSUInteger taskIdentifier;
    LLNWFileUploadTask *task = [LLNWFileUploadTask taskWithAudioFile:audioFile withObserver:self withTaskIdentifier:&taskIdentifier];
    
    if (!task) {
        LLLog(@"LLAudioNetwork 不能开始一个空的上传任务");
        return;
    }
    
    //自定义HttpHeader
    NSDictionary *customHeaders = @{@"interface": @"UploadImages"};
    task.customRequestHeader = customHeaders;
    
    [self.uploadTasksArray addObject:@(taskIdentifier)];
    
    if (self.uploadManager) {
        
        [self.uploadManager addTask:task];
        
        LLLog(@"LLAudioNetwork task:%lu begin upload .... ",(unsigned long)taskIdentifier);
    }
    
}

- (void)downloadAudioFile:(LLAudioModel *)audioFile
{
    /* 创建下载任务开始下载 */
    NSUInteger taskIdentifier;
    LLNWFileDownloadTask *task = [LLNWFileDownloadTask taskWithAudioFile:audioFile withObserver:self getTaskIdentifier:&taskIdentifier];
    
    [self.downloadTasksArray addObject:@(taskIdentifier)];
    
    [[LLNWFileDownloadManager shareDownloadManager] addTask:task];
    
    LLLog(@"LLAudioNetwork task:%lu begin dowload .... ",(unsigned long)taskIdentifier);
}

- (void)downloadAudioFileWithUrl:(NSString *)remoteAudioUrl withFinishDownloadPlayCheck:(BOOL)finishPlay withFileUniqueIdentifier:(NSString **)fileUniqueIdentifier
{
    LLAudioModel *audioFile = [[LLAudioModel alloc]init];
    audioFile.remotePath = remoteAudioUrl;
    audioFile.isNeedConvertEncodeToSave = YES;
    audioFile.shouldPlayWhileFinishDownload = finishPlay;
    audioFile.isDeleteWhileFinishConvertToLocalFormate = YES;
    *fileUniqueIdentifier = audioFile.uniqueIdentifier;
    
    [self downloadAudioFile:audioFile];
}

- (void)downloadAudioFileWithUrl:(NSString *)remoteAudioUrl withFileUniqueIdentifier:(NSString **)fileUniqueIdentifier
{
    [self downloadAudioFileWithUrl:remoteAudioUrl withFinishDownloadPlayCheck:NO withFileUniqueIdentifier:fileUniqueIdentifier];
}

@end
